home *** CD-ROM | disk | FTP | other *** search
/ FishMarket 1.0 / FishMarket v1.0.iso / fishies / 301-325 / disk_313 / uucp / uucp1.lzh / src / MUtil / trimfile.c < prev   
C/C++ Source or Header  |  1990-01-10  |  2KB  |  106 lines

  1.  
  2. /*
  3.  *  TRIMFILE file1 file2 .. filen -lines
  4.  *
  5.  *  (C) Copyright 1989-1990 by Matthew Dillon,  All Rights Reserved.
  6.  *
  7.  *  Trims the specified files to the specified number of lines.  Each
  8.  *  file is read and the last N lines written back.
  9.  *
  10.  *  Normally used to trim log files based on a crontab entry.  If no
  11.  *  -lines argument is given the file is trimmed to 100 lines.
  12.  *
  13.  *  Each line may be up to 255 characters in length.
  14.  */
  15.  
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18.  
  19. #define LINSIZE 256
  20.  
  21. char    **LineBuf;
  22. long    Lines = 100;
  23.  
  24. void    MemErr();
  25. void    TrimFile();
  26.  
  27. void
  28. main(ac, av)
  29. char *av[];
  30. {
  31.     short i;
  32.     for (i = 1; i < ac; ++i) {
  33.     if (av[i][0] == '-')
  34.         Lines = atol(av[i] + 1);
  35.     }
  36.     if (Lines < 0) {
  37.     fprintf(stderr, "Illegal line specification %d\n", Lines);
  38.     exit(1);
  39.     }
  40.  
  41.     /*
  42.      *    Allocating one more than necessary handles the Lines == 0 case
  43.      *    as well as supplying a scratch buffer for the last fgets that
  44.      *    fails.
  45.      */
  46.  
  47.     LineBuf = malloc(sizeof(char *) * (Lines + 1));
  48.     if (LineBuf == NULL)
  49.     MemErr();
  50.     for (i = 0; i <= Lines; ++i) {
  51.     LineBuf[i] = malloc(LINSIZE);
  52.     if (LineBuf[i] == NULL)
  53.         MemErr();
  54.     }
  55.     for (i = 1; i < ac; ++i) {
  56.     char *ptr = av[i];
  57.  
  58.     if (*ptr == '-')
  59.         continue;
  60.     TrimFile(ptr);
  61.     }
  62. }
  63.  
  64. void
  65. MemErr()
  66. {
  67.     fprintf(stderr, "Not enough memory!\n");
  68.     exit(1);
  69. }
  70.  
  71. void
  72. TrimFile(name)
  73. char *name;
  74. {
  75.     FILE *fi = fopen(name, "r");
  76.     long rep;
  77.     long i;
  78.  
  79.     if (fi == NULL)
  80.     return;
  81.  
  82.     i = 0;
  83.     rep = 0;
  84.     while (fgets(LineBuf[i], LINSIZE, fi)) {
  85.     if (++i > Lines) {
  86.         i = 0;
  87.         rep = 1;
  88.     }
  89.     }
  90.     fclose(fi);
  91.  
  92.     if (rep == 0)
  93.     return;
  94.  
  95.     if (fi = fopen(name, "w")) {
  96.     long j;
  97.     for (j = Lines; j; --j) {
  98.         if (++i > Lines)
  99.         i = 0;
  100.         fputs(LineBuf[i], fi);
  101.     }
  102.     fclose(fi);
  103.     }
  104. }
  105.  
  106.